import { receiptRecord, refreshSmsSendRecord } from '@/services/api/api-instruct-record';
import {
  CheckSquareOutlined,
  CloseCircleOutlined,
  QuestionCircleOutlined,
} from '@ant-design/icons';
import { DrawerForm } from '@ant-design/pro-form';
import { Button, Col, Flex, message, Popover, Row, Space, Typography } from 'antd';
import Tree, { DataNode } from 'antd/lib/tree';
import { useState } from 'react';
import ListReceipt from './ListReceipt';
import Reminders from './Reminders';

interface ReceiptAssignProps {
  id: string;
  deadlineTime: string;
  receipt: string;
  type: 'read' | 'receipt';
  isRun: boolean;
}

const ReceiptAssign: React.FC<ReceiptAssignProps> = ({
  id,
  receipt,
  deadlineTime,
  type,
  isRun,
}) => {
  const [dataTree, setDataTreeState] = useState<DataNode[]>();
  const [dataCheckTree, setDataCheckTreeState] = useState<any>();

  const checkTreeKeys = new Array();

  const [createdCombineId, setCreatedCombineIdState] = useState<string>();

  const [selectTreeCreatedOrganization, setTreeCreatedOrganizationState] = useState<{
    id: string;
    name: string;
  }>();


  const [treeSelectedKeys, setTreeSelectedKeys] = useState<string[]>([]);
  const [treeDefaultExpandedKeys, setTreeDefaultExpandedKeys] = useState<string[]>([]);


  /**
   * 加载组织树请求网络
   */
  const loadData = async () => {
    try {
      const response = await receiptRecord({ id, type: type === 'read' ? 1 : 2 });

      if (response.code === 0) {
        setDataTreeState(readyTreeData(response.data));
        setDataCheckTreeState(checkTreeKeys);
      }
    } catch (error) { }
  };

  const loadRefreshSmsSendRecord = async () => {
    const response = await refreshSmsSendRecord({ instructId: id });

    if (response.code === 0) {
      message.success('更新成功');
      setTimeout(() => {
        loadData();
      }, 500);
    }
  };

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: Array<UserData.Organization>): any {
    const treeData = new Array();

    if (data) {

      let defaultExpandedKeys = new Array();

      data.forEach((val, idx, array) => {

        if (val.parentId == '0') {
          defaultExpandedKeys.push(val.id)
        }

        treeData.push({
          title: (
            <Space>
              {val.name}
              {val?.smsPhone != undefined && (
                <>
                  -
                  <Typography.Paragraph
                    copyable
                    style={{
                      marginBottom: 0,
                    }}
                  >
                    {val.smsPhone}
                  </Typography.Paragraph>
                </>
              )}
              {val.isOrganization == 0 ? (
                val.smsSendStatus == undefined ? (
                  ''
                ) : val.smsSendStatus == 1 ? (
                  <Popover
                    style={{
                      maxWidth: '50px',
                    }}
                    content={
                      <div>
                        <p>
                          {val.name} {val.smsPhone}
                        </p>
                      </div>
                    }
                    title={'正在发送中...'}
                  >
                    {/* <LoadingOutlined /> */}
                  </Popover>
                ) : val.smsSendStatus == 2 ? (
                  <Popover
                    style={{
                      maxWidth: '50px',
                    }}
                    content={
                      <div>
                        <p>
                          {val.name} {val.smsPhone}
                        </p>
                        <p>{val.smsSuggestion}</p>
                      </div>
                    }
                    title={val.smsReason}
                  >
                    <CloseCircleOutlined
                      style={{
                        color: '#FF4D4F',
                      }}
                    />
                  </Popover>
                ) : (
                  ''
                )
              ) : (
                ''
              )}
            </Space>
          ),
          key: val.id,
          name: val.name,
          isOrganization: val.isOrganization,
          parentId: val.parentId,
          icon: val.isView === 1 ? <CheckSquareOutlined /> : <QuestionCircleOutlined />,
          children: readyTreeData(val.children as Array<UserData.Organization>),
        });

        if (val.isView !== undefined && val.isView === 1 && !val.children) {
          checkTreeKeys.push(val.id);
        }
      });

      setTreeDefaultExpandedKeys(defaultExpandedKeys)
    }
    return treeData;
  }

  return (
    <DrawerForm
      title={
        <Flex justify={'space-between'} align={'center'}>
          {type === 'receipt' ? <span>回执情况</span> : <span>阅读情况</span>}
          <Space>
            <Button
              type="primary"
              onClick={async () => {
                loadRefreshSmsSendRecord();
              }}
            >
              更新短信回执
            </Button>
            {isRun && <Reminders type={type} id={id} isRun={isRun} />}
          </Space>
        </Flex>
      }
      trigger={<a>{receipt}</a>}
      drawerProps={{
        size: 'large',
        forceRender: true,
        destroyOnClose: true,
        width: '1000px',
      }}
      submitter={false}
      onOpenChange={(visible) => {
        if (visible) {
          loadData();
        } else {
          setDataTreeState([]);
        }
      }}
    >
      {dataTree && dataTree?.length > 0 ? (
        <Row>
          <Col span={10}>
            <Tree
              treeData={dataTree}
              checkedKeys={dataCheckTree}
              checkable
              selectedKeys={treeSelectedKeys}
              style={{ width: '100%' }}
              // defaultExpandAll={true}
              defaultExpandedKeys={treeDefaultExpandedKeys}
              onSelect={(selectedKeys, info) => {
                console.log('==1111==', info);

                if (info.selected && info.node.isOrganization == 1 && info.node.parentId != '0') {
                  console.log('==2222==', info);
                  setTreeCreatedOrganizationState({
                    id: info.node.key,
                    name: info.node.name,
                  })
                  setTreeSelectedKeys([info.node.key])
                } else {
                  setTreeCreatedOrganizationState(undefined)
                  setTreeSelectedKeys([])
                }

                if (info.selected && info.node.checked) {
                  setCreatedCombineIdState(info.node.key as string);
                }
              }}
            />
          </Col>
          <Col span={14}>
            <ListReceipt
              type={type === 'read' ? 1 : 2}
              recordId={id}
              deadlineTime={deadlineTime}
              createdCombineId={createdCombineId}
              createdOrganization={selectTreeCreatedOrganization}
              onSelelctCreatedOrganization={(createdOrganizationId) => {
                setTreeSelectedKeys([createdOrganizationId])
              }}
              onCloseCreatedOrganization={() => {
                setTreeSelectedKeys([])
              }}
            />
          </Col>
        </Row>
      ) : (
        '暂无数据'
      )}
    </DrawerForm>
  );
};

export default ReceiptAssign;
